﻿<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF Binding Validation Rule Demo" Height="150" Width="300"
    xmlns:local="clr-namespace:ValidationRuleDemo">
    <Window.Resources>
        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Margin="5,0,5,0" Foreground="Red" 
                           FontSize="16" VerticalAlignment="Center" 
                           Text="*" 
                           ToolTip="{Binding ElementName=errorAdorner, 
                            Path=AdornedElement.(Validation.Errors).CurrentItem.ErrorContent}" />

                <AdornedElementPlaceholder x:Name="errorAdorner" />
            </DockPanel>
        </ControlTemplate>

        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Validation.ErrorTemplate" Value="{DynamicResource validationTemplate}" />
        </Style>
    </Window.Resources>
    <Grid>
        <TextBlock Height="21" HorizontalAlignment="Left" 
                   Margin="12,27,0,0" VerticalAlignment="Top" 
                   Width="66" Text="First Name" />
        
        <TextBox Height="23" Margin="92,24,0,0" VerticalAlignment="Top" 
                 HorizontalAlignment="Left" Width="120">
            <TextBox.Text>
                <Binding Path="FirstName" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <!-- the FieldTag property allows easy identification of the source control-->
                        <local:RequiredEntryValidationRule FieldTag="First Name" />
                    </Binding.ValidationRules>
                </Binding> 
            </TextBox.Text>
        </TextBox>

        <TextBlock Height="21" HorizontalAlignment="Left" Margin="12,54,0,0" VerticalAlignment="Top" Width="66" Text="Last Name" />
        <TextBox Height="23" Margin="92,53,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120">
            <TextBox.Text>
                <Binding Path="LastName" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <local:RequiredEntryValidationRule FieldTag="Last Name" />
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
    </Grid>
</Window>
